package dao

import "2302a/testyuekao/global"

func Create[T any](data *T) bool {

	if err := global.DB.Create(&data).Error; err != nil {
		return false
	}
	return true
}

func Delete[T any](data *T) bool {
	if err := global.DB.Delete(&data).Error; err != nil {
		return false
	}
	return true
}

func GetListPageByFields[T any](where *T, page uint, pageSize uint, out *[]T) bool {
	if page <= 0 {
		page = 1
	}
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	query := global.DB.Model(out).Where(where)
	if err := query.Where(offset).Limit(int(pageSize)).Order(&out).Find(&out).Error; err != nil {
		return false
	}
	return true
}
func GetListByFields[T any](where *T, data *[]T) bool {
	if err := global.DB.Where(where).Find(&data).Error; err != nil {
		return false
	}
	return true
}
func GetOneByFields[T any](where *T, data *T) bool {
	if err := global.DB.Where(where).Find(&data).Limit(1).Error; err != nil {
		return false
	}
	return true
}

func GetOneById[T any](id uint, data *T) bool {
	if err := global.DB.Where("id=?", id).Find(&data).Limit(1).Error; err != nil {
		return false
	}
	return true
}

func Update[T any](data *T) bool {
	if err := global.DB.Updates(&data).Error; err != nil {
		return false
	}
	return true
}
